package com.css.bjdt_report.explain.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.nutz.dao.sql.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.css.bjdt_report.explain.entity.RptCellExplain;
import com.css.bjdt_report.explain.entity.RptExplainAreaTemporary;
import com.css.bjdt_report.explain.entity.RptTemplateExplain;
import com.css.bjdt_report.explain.service.ReportTemplateExplainService;
import com.css.bjdt_report.explain.service.RptCellExplainService;
import com.css.bjdt_report.explain.service.RptExplainAreaTemporaryService;
import com.css.bjdt_report.util.CommonUtil;
import com.css.bjdt_report.util.JsonResult;
import com.css.bjdt_report.util.PropertyFilter;

//报表版本维护Controller
@Controller
@RequestMapping(value = "/reportTemplateExplainController")
public class ReportTemplateExplainController {

	@Autowired
	private ReportTemplateExplainService reportTemplateExplainService;

	@Autowired
	private RptCellExplainService rptCellExplainService;

	@Autowired
	private RptExplainAreaTemporaryService rptExplainAreaTemporaryService;

	@RequestMapping("/explainList")
	public String explainList() {
		return "report-explain/report-explain-list";
	}

	//查询报表模板，并生成LIGERUI格式的json
	@ResponseBody
	@RequestMapping("/explainListData/{annualId}")
	public Map explainListData(@PathVariable String annualId, HttpServletRequest request,
			@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize,
			@RequestParam(value = "sortname") String sortname, @RequestParam(value = "sortorder") String sortorder) {
		Criteria cnd = PropertyFilter.cri(request);

		cnd.where().and("ANNUAL_ID", "=", annualId);

		cnd.getOrderBy().desc("ORDER_ID");

		return reportTemplateExplainService.queryPage(cnd, pageNum, pageSize);
	}

	@RequestMapping("/preCreateExplain/{annualId}")
	public String preCreateExplain(@PathVariable String annualId, Model model) {
		RptTemplateExplain rptTemplateExplain = new RptTemplateExplain();
		rptTemplateExplain.setAnnualId(annualId);
		model.addAttribute("rptTemplateExplain", rptTemplateExplain);
		return "report-explain/report-explain-input";
	}

	//保存报表说明
	@RequestMapping(value = "/insertExplain", method = RequestMethod.POST)
	public String insertExplain(RptTemplateExplain rptTemplateExplain, Model model) {
		reportTemplateExplainService.saveAExplain(rptTemplateExplain);
		model.addAttribute("message", "操作成功");
		return "report-explain/report-explain-input";
	}

	@RequestMapping("/preUpdateExplain/{id}")
	public String preUpdateExplain(@PathVariable String id, Model model) {
		RptTemplateExplain rptTemplateExplain = reportTemplateExplainService.getARptTemplateExplain(id);
		model.addAttribute("rptTemplateExplain", rptTemplateExplain);
		return "report-explain/report-explain-input";
	}

	//修改报表说明
	@RequestMapping(value = "/updateExplain", method = RequestMethod.POST)
	public String updateExplain(RptTemplateExplain rptTemplateExplain, Model model) {
		reportTemplateExplainService.updateRptTemplateExplain(rptTemplateExplain);
		model.addAttribute("message", "操作成功");
		return "report-explain/report-explain-input";
	}

	//删除一个报表模板
	@ResponseBody
	@RequestMapping(value = "/deleteRptExplain/{id}")
	public String deleteRptExplain(@PathVariable String id) {
		reportTemplateExplainService.delete(id);
		return "success";
	}

	//读取报表说明模板
	@RequestMapping("/readReportTemplateExplain/{explainId}/{annualId}")
	public void readReportTemplate(@PathVariable String explainId, @PathVariable String annualId,
			HttpServletRequest request, HttpServletResponse res) {
		String url = CommonUtil.readProperties();
		//String uploadPath = getUploadPath(request);
		String fileName = explainId + ".cll";
		File cellFile = new File(url + "/" + annualId + "/explain" + "/", fileName);
		if (cellFile.exists()) {
			OutputStream os = null;
			try {
				os = res.getOutputStream();
				os.write(FileUtils.readFileToByteArray(cellFile));
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@RequestMapping(value = "/preReportExplainDesign/{explainId}/{annualId}", method = RequestMethod.GET)
	public String preReportExplainDesign(@PathVariable String explainId, @PathVariable String annualId, Model model) {
		model.addAttribute("id", explainId);
		model.addAttribute("annualId", annualId);
		return "/report-explain/report-explain-design";
	}

	//保存单元格属性
	@ResponseBody
	@RequestMapping(value = "/saveReportExplainAllCell/{explainId}/{annualId}", method = RequestMethod.POST)
	public void saveReportAndCellType(@PathVariable String explainId, @PathVariable String annualId,
			@RequestParam(value = "jsonText") String cellJson,
			@RequestParam(value = "reportExplainCategoryText") String reportExplainCategoryText, Model model) {
		try {
			List<RptExplainAreaTemporary> rptExplainAreaTemporaryList = new ArrayList<RptExplainAreaTemporary>();
			//解析报表的数据区域
			JsonResult reportExplainCategoryResult = new JsonResult();
			Map<String, String> reportExplainCategoryMap = reportExplainCategoryResult
					.jsonToString(reportExplainCategoryText);
			Set<String> reportExplainCategoryKey = reportExplainCategoryMap.keySet();
			for (String strKey : reportExplainCategoryKey) {
				String strJson = "{" + reportExplainCategoryMap.get(strKey) + "}";
				JSONObject reportCategoryJobj = new JSONObject(strJson);
				String absStartCol = reportCategoryJobj.getString("absStartCol");
				String absEndCol = reportCategoryJobj.getString("absEndCol");
				String absStartRow = reportCategoryJobj.getString("absStartRow");
				String absEndRow = reportCategoryJobj.getString("absEndRow");
				String explainIdJosn = reportCategoryJobj.getString("explainId");
				String temporaryDescribe = reportCategoryJobj.getString("temporaryDescribe");
				//先塞数据区域的东西
				RptExplainAreaTemporary rptExplainAreaTemporary = new RptExplainAreaTemporary();
				rptExplainAreaTemporary.setId(CommonUtil.getUUID());
				rptExplainAreaTemporary.setAbsStartCol(absStartCol);
				rptExplainAreaTemporary.setAbsEndCol(absEndCol);
				rptExplainAreaTemporary.setAbsStartRow(absStartRow);
				rptExplainAreaTemporary.setAbsEndRow(absEndRow);
				rptExplainAreaTemporary.setTemporaryDescribe(temporaryDescribe);
				rptExplainAreaTemporary.setExplainId(explainIdJosn);
				rptExplainAreaTemporaryList.add(rptExplainAreaTemporary);
			}

			//再塞单元格的属性
			List<RptCellExplain> cellExplainList = new ArrayList<RptCellExplain>();
			JsonResult jsonResult = new JsonResult();
			Map<String, String> map = jsonResult.jsonToString(cellJson);
			Set<String> key = map.keySet();
			for (String strKey : key) {
				String strJson = "{" + map.get(strKey) + "}";
				JSONObject jobj = new JSONObject(strJson);
				RptCellExplain rptCellExplain = new RptCellExplain();
				rptCellExplain.setExplainId(explainId);
				rptCellExplain.setAbsColNum(Integer.parseInt(jobj.getString("absolutelyCol")));
				rptCellExplain.setAbsRowNum(Integer.parseInt(jobj.getString("absolutelyRow")));
				cellExplainList.add(rptCellExplain);
			}

			reportTemplateExplainService.saveRptExplainAreaCategoryCell(cellExplainList, rptExplainAreaTemporaryList,
					explainId);
		} catch (Exception e) {
			e.getMessage();
		}
	}

	//保存报表说明模板
	@RequestMapping(value = "/saveReportExplain/{explainId}/{annualId}", method = RequestMethod.POST)
	public void saveReportExplain(@PathVariable String explainId, @PathVariable String annualId,
			HttpServletRequest request) {
		String url = CommonUtil.readProperties();
		//String uploadPath = getUploadPath(request);
		File directory = new File(url, annualId);
		if (!directory.exists()) {
			directory.mkdir();
		}
		String fileName = explainId + ".cll";
		File cellFile = new File(directory.getPath() + "/explain", fileName);
		if (cellFile.exists()) {
			cellFile.delete();
		}
		try {
			FileUtils.copyInputStreamToFile(request.getInputStream(), cellFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//通过报表ID，获得当前报表单元格的所有属性
	@ResponseBody
	@RequestMapping(value = "/queryReportAndCellExplain/{explainId}", method = RequestMethod.POST)
	public List<RptCellExplain> queryReportAndCellExplain(@PathVariable String explainId) {
		List<RptCellExplain> cellExplainList = rptCellExplainService.queryAllCellExplainByExplainId(explainId);
		return cellExplainList;
	}

	//通过报表ID，获得当前报表单元格的所有数据区域
	@ResponseBody
	@RequestMapping(value = "/queryReportExplainAreaTemporary/{explainId}", method = RequestMethod.POST)
	public List<RptExplainAreaTemporary> queryReportExplainAreaTemporary(@PathVariable String explainId) {
		return rptExplainAreaTemporaryService.getAllRptExplainAreaTemporaryByExplainId(explainId);
	}
}
